package com.game.service.game.turntable.email;

import com.game.service.app.PostJson;
import com.game.service.app.get_score.JsonBean;
import com.game.service.db.UserScoreDaoImpl;
import com.game.service.socket.FileUtils;
import com.game.service.windows.LogWindows;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import static com.game.service.app.Score.doPostForm;
import static com.game.service.app.Utils.LogDate;
import static com.game.service.define.RoomConfig.*;

public class EmailDeal {

    static EmailDeal instance;
    public static final String EMAIL_TYPE_MATCH = "Rewards";
    public static final String EMAIL_TYPE_DAILY_TASK = "DailyTask";
    public static final String EMAIL_TYPE_EXCHANGE = "StoreExchange";


    private ISendListener mISendListener;

    public void addListener(ISendListener mISendListener) {
        this.mISendListener = mISendListener;
    }

    /*** 创建邮件-可领取
     *
     * @param json
     * @param url
     * @param desc
     * @param orderId
     * @param uid
     */
    public void create(String json, String url, String desc, String orderId, int uid) {
        PostJson postJson = new PostJson();
        long time = System.currentTimeMillis();
        postJson.setPid(orderId);
        postJson.setGameid(GAME_ID);
        postJson.setUid(uid);
        postJson.setPostJson(json);
        postJson.setPostResult(0);
        postJson.setPostUrl(url);
        postJson.setJsonDesc(desc);
        postJson.setAddCurrentTimeMillis(time);
        UserScoreDaoImpl.getInstance().addEmail(postJson);//添加到数据库
    }

    /*** 记录邮件-已经领取
     *
     * @param json
     * @param url
     * @param desc
     * @param orderId
     * @param uid
     */
    public void record(String json, String url, String desc, String orderId, int uid) {
        PostJson postJson = new PostJson();
        long time = System.currentTimeMillis();
        postJson.setPid(orderId);
        postJson.setGameid(GAME_ID);
        postJson.setUid(uid);
        postJson.setPostJson(json);
        postJson.setPostResult(1);//表示已经发送只做记录
        postJson.setPostUrl(url);
        postJson.setJsonDesc(desc);
        postJson.setAddCurrentTimeMillis(time);
        UserScoreDaoImpl.getInstance().addEmail(postJson);//添加到数据库
    }


    private void post(PostJson json, int maxPost) {
        if (json.getPostResult() != 0) {//不等于0时表示已经处理成功
            return;
        }
        if (maxPost-- == 0) {
            FileUtils.writeTxtToFile("发送失败,等待下次发送" + json, LogDate(), LOG_NAME_FAIL_JSON);
            return;
        }

        int finalMaxPost = maxPost;
        new Thread(() -> {
            String result = doPostForm(json.getPostUrl(), json.getPostJson());
            String log = "发送结果,第" + (EXIT_MAX_POST - finalMaxPost) + "次,id=" + json.getPid() + "返回=" + result;
            FileUtils.writeTxtToFile(log, LogDate(), LOG_NAME_POST_JSON);

            if (result.isEmpty()) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                post(json, finalMaxPost);
                return;
            }
            Type type0 = new TypeToken<JsonBean>() {
            }.getType();
            JsonBean bean = new Gson().fromJson(result, type0);
            if (bean != null && (bean.code == 0 || bean.code == 1001)) {
                //备注:服务器标记为0的表示处理成功，1001的表示重复发送(此时更新本地数据库为成功状态1)
                UserScoreDaoImpl.getInstance().updateEmail(json.getPid());
                if (mISendListener != null) {
                    mISendListener.sendSuccess();//发送成功
                }

                FileUtils.writeTxtToFile("数据发送,发送成功:" + json, LogDate(), LOG_NAME_POST_JSON);
                LogWindows.getLogWindows().printToTextArea("Email系统-领取成功" + json, EmailDeal.class);

            }

        }).start();
    }

    /*** 处理邮件 ,当订单为AllClaimed表示全部领取
     *
     * @param pid 订单id
     */
    public void dealEmail(int uid, String pid) {
        if (pid == null) {
            return;
        }
        List<PostJson> dbList;
        if (pid.equals("AllClaimed")) {
            dbList = UserScoreDaoImpl.getInstance().getEmailList(GAME_ID, uid);
        } else {
            PostJson postJson = UserScoreDaoImpl.getInstance().getEmail(pid);
            List<PostJson> onlyOne = new ArrayList<>();
            onlyOne.add(postJson);
            dbList = onlyOne;
        }

        long current = System.currentTimeMillis();
        //去数据里查询==0的未发送的数据进行清零

        if (dbList.isEmpty()) {
            LogWindows.getLogWindows().printToTextArea("Email系统-异常查询", EmailDeal.class);
            return;
        }
        LogWindows.getLogWindows().printToTextArea("Email系统-领取邮件奖励" + dbList.size(), EmailDeal.class);

        for (PostJson postJson : dbList) {

            if (postJson.getPostResult() == 0) {
                //防止重复发送,必须间隔3000ms
                long time = current - postJson.getAddCurrentTimeMillis();
                if (time > 3000) {
                    System.out.println("间隔时间=" + time + ",发送=" + postJson);
                    post(postJson, EXIT_MAX_POST);
                }

            }

        }

    }


    /*** 删除邮件 ,当订单为AllClaimed表示全部领取
     *
     * @param pid 订单id
     */
    public void deleteEmail(int uid, String pid) {
        if (pid == null) {
            return;
        }

        if (pid.equals("AllDelete")) {
            UserScoreDaoImpl.getInstance().deleteAllEmail(uid);
        } else {
            UserScoreDaoImpl.getInstance().deleteEmail(pid);

        }

    }

    public interface ISendListener {
        void sendSuccess();

        void error(String e);
    }

}
